<script lang="ts" setup>
import { computed, onMounted, PropType, reactive } from 'vue'
import { Command } from '@/commands/command.ts'
import { dbus } from '@/dbus/dbus.ts'
import showdown from 'showdown'
import { Event, listen } from '@tauri-apps/api/event'
import { Command as ModelCommand } from '@/models/command.ts'

const props = defineProps({
    command: { required: true, type: Object as PropType<Command> },
})

const state = reactive<{ message: string; input: number; output: number }>({ message: '', input: 0, output: 0 })
const html_content = computed(() => {
    return new showdown.Converter().makeHtml(state.message)
})

onMounted(async () => {
    if (props.command!.waiting) {
        // 注册监听器
        await listen(`ai-message-${props.command!.id}`, (message: Event<ModelCommand>) => {
            state.message = message.payload.output

            const statistic = JSON.parse(message.payload.statistic) as { input_tokens: number; output_tokens: number }
            if (statistic.input_tokens) {
                state.input = statistic.input_tokens
            }
            if (statistic.output_tokens) {
                state.output = statistic.output_tokens
            }

            dbus.emit('scroll-to-bottom')
        })

        // 处理命令
        props
            .command!.execute()
            .finally(async () => (state.message = props.command!.output))
            .finally(async () => dbus.emit('scroll-to-bottom'))

        return
    }

    state.message = props.command!.output

    const statistic = JSON.parse(props.command!.statistic) as { input_tokens: number; output_tokens: number }
    if (statistic.input_tokens) {
        state.input = statistic.input_tokens
    }
    if (statistic.output_tokens) {
        state.output = statistic.output_tokens
    }

    dbus.emit('scroll-to-bottom')
})
</script>

<template>
    <n-space :size="3" :wrap-item="false" vertical>
        <n-space :wrap-item="false" class="session-message" vertical>
            <div class="ai-message" v-html="html_content"></div>
        </n-space>
        <n-space :wrap="false" :wrap-item="false" align="center">
            <n-text class="desc-button">INPUT TOKENS: {{ state.input }}</n-text>
            <n-text class="desc-button">OUTPUT TOKENS: {{ state.output }}</n-text>
        </n-space>
    </n-space>
</template>

<style lang="scss" scoped></style>
